package smartnews.model.dao.mysql;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.logging.Level;
import java.util.logging.Logger;

import smartnews.model.dao.db.UserDb;
import smartnews.model.entity.User;



public class UserDbMySql implements UserDb {
	private Connection con;

	public UserDbMySql(Connection con) {
		this.con = con;
	}

	public User getUserById(String id) {
		// TODO Auto-generated method stub
		String sql = "SELECT * FROM user WHERE id = '"+ id +"'";
		
		Statement stm = null;
		ResultSet result = null;
		User user = new User();
		
		
		try {
			
			stm = con.createStatement();
			result = stm.executeQuery(sql);
			
			
			while (result.next()){
				user.setId(id);
				user.setEmail(result.getString("Email").toString());
				user.setPicture(result.getString("Picture").toString());
			}
			
			
			stm.close();
			
		} catch (SQLException ex) {
			ex.printStackTrace();
		}

		return user;
	}

	public boolean updateUser(User user) {
		// TODO Auto-generated method stub
		String sql = "UPDATE user SET Email = ?, Picture = ? WHERE id = ?";
		
		try {
			
			PreparedStatement pst = con.prepareStatement(sql);
			
			pst.setString(1, user.getEmail());
			pst.setString(2,  user.getPicture());
			pst.setString(3, user.getId());
			pst.executeUpdate();
		
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
				
		return true;
	}

	public void insertUser(User user) {
		String sql = "INSERT INTO user(id, Email, Picture) values(?, ?, ?)";
		
		try {
			PreparedStatement statement = con.prepareStatement(sql);
			statement.setString(1, user.getId());
			statement.setString(2, user.getEmail());
			statement.setString(3, user.getPicture());
			statement.executeUpdate();
			statement.close();
		} catch (SQLException ex) {
			ex.printStackTrace();
		}

	}
}
